<template>
  <div >
    <el-form-item label="跳转功能">
        <l-tree-select :options="modulesTree"  v-model="config.moduleId" >
        </l-tree-select>
    </el-form-item>
    <el-form-item label="表单选择" prop="f_FormCode">
        <l-custmerform-select
            v-model="config.viewForm"
            @change="custmerformChange"
            :placeholder="$t('请选择')"
            >
        </l-custmerform-select>
    </el-form-item>
    <el-form-item label="表单版本" prop="f_FormVerison">
        <l-select
            v-model="config.formVerison"
            :options="formVerisons"
            :placeholder="$t('请选择')"
            >
        </l-select>
    </el-form-item>
    <el-form-item label="排序字段">
        <l-select
            v-model="config.orderId"
            :options="formComponents"
            placeholder="请选择"
            >
        </l-select>
    </el-form-item>
    <el-form-item label="行数限制">
        <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="config.limitRow"
            >
        </el-switch>
    </el-form-item>
    <el-form-item v-if="config.limitRow == 1" label="最大行数">
        <el-input-number v-model="config.maxRows"
            controls-position="right"
            placeholder="请输入"></el-input-number>
    </el-form-item>
    <el-divider>数据列</el-divider>
    <div class="reg-item" :key="item.id" v-for="(item,index) in data.columns" >
        <el-form-item label="绑定字段" style="margin-bottom:8px;" >
            <l-select v-model="item.prop"   :options="formComponents" @change="handleChangeSelect($event,item)" ></l-select>
        </el-form-item>
        <el-form-item label="宽度" style="margin-bottom:8px;" >
            <el-input v-model="item.width"
                    placeholder="请输入">
                <template slot="append">%</template>        
            </el-input>
        </el-form-item>
        <el-form-item label="对齐" style="margin-bottom:0;" >
            <l-select v-model="item.align" :options="alignOptions" ></l-select>
        </el-form-item>

        <el-button title="删除"
                    @click="handleRemoveCol(index)"
                    class="reg-item-delete"
                    circle
                    plain
                    size="mini"
                    type="danger">
            <i class="el-icon-close"></i>
        </el-button>
    </div>
    <div class="mt-8" >
        <el-button class="ml-8" type="primary" size="mini" @click="handleAddCol"  >添加列</el-button>
    </div>

    <div class="mt-8" >
        <el-button class="ml-8" type="primary" size="mini" @click="handleSettingCondition"  >设置跳转条件</el-button>
    </div>

    <l-dialog 
        title="设置跳转条件"
        :visible.sync="formVisible"
        :height="528"
        :width="720"
        @ok="handleSave"
        @close="handleCloseForm"
        @opened="handleOpenedForm"
        >
        <my-form ref="form" ></my-form>       
    </l-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
const apiForm = window.$api.custmerForm.scheme;
import MyForm from '../conditionForm.vue'
export default {
    props: ['data'],
    inject: ["quickBiDesign"],
    components:{
        MyForm
    },
    data () {
        return {
            alignOptions:[{value:'left',label:'靠左'},{value:'center',label:'居中'},{value:'right',label:'靠右'}],
            formVisible:false
        }
    },
    computed:{
        config(){
            return this.data
        },
        ...mapGetters(["modules"]),
        myModules(){
            //if(this.loginInfo.f_SecurityLevel == 1){
                return this.modules.filter(t=>t.f_EnabledMark == 1)
            //}
            /*return this.modules.filter(item =>{
                if(item.f_EnabledMark == 1){
                    const moduleAuthIds = this.loginInfo.moduleAuthIds || []
                    if(moduleAuthIds.indexOf(item.f_ModuleId) > -1){
                        return true
                    }
                    else{
                        return false
                    }
                }
                else{
                    return false
                }
            })*/
        },
        modulesTree(){
            const res = this.$toTree(this.myModules,"f_ModuleId","f_ParentId","f_ModuleId","f_FullName")
            return res.filter(t=>t.f_ParentId == '0')
        }
    },
    asyncComputed:{
      formVerisons:{
        async get(){
            let res = []
            if(!this.$validatenull(this.config.viewForm)){
              res = await this.$awaitWraper(apiForm.getHistoryList(this.config.viewForm))
            }
            return (res || []).map(t=>{return {label:this.lr_dateFormat(t.f_CreateDate),value:t.f_Id }})
        }
      },
      formComponents:{
        async get(){
            if(this.$validatenull(this.config.formVerison)){
                return []
            }
            if(this.$validatenull(this.quickBiDesign.custmerformSchemes[this.config.formVerison])){
                const {f_Scheme,f_Id} = (await this.$awaitWraper(apiForm.getHistory(this.config.formVerison))) || {}
                this.quickBiDesign.custmerformSchemes[f_Id] = {f_Scheme}
                if(this.config.formVerison == f_Id){
                    return this.loadFormScheme(f_Scheme)
                }
            }
            else{
                return this.loadFormScheme(this.quickBiDesign.custmerformSchemes[this.config.formVerison].f_Scheme);
            }
            return []
        }
      }
    },
    methods:{
        custmerformChange(val){
            if(val == null){
                this.config.formVerison = ''
            }
            else{
                this.config.formVerison = val.f_SchemeId
            }            
        },
        handleAddCol(){
            this.config.columns.push({
                id:this.$uuid(),
                prop:'',
                width:25,
                align:'left'
            })
        },
        handleRemoveCol(index){
            this.config.columns.splice(index,1)
        },
        loadFormScheme(strScheme){
            const scheme = JSON.parse(strScheme)
            const fields = []
            scheme.formInfo.tabList.forEach(tab => {
                tab.components.forEach(component =>{
                    if(!['gridtable','divider','btn','card'].includes(component.type) && component.display && component.field){
                        //console.log(component.field,'component.field')
                        const col = {
                            value:`${component.field.toLowerCase()}${scheme.formType==1?'':scheme.db.findIndex(t=>t.name == component.table)}`,
                            label:component.label
                        }

                        const dataTypeRes = this.getComponentDataType(component)
                        col.dataType = dataTypeRes.dataType
                        col.dataCode = dataTypeRes.code
                        col.valueKey = dataTypeRes.valueKey
                        col.labelKey = dataTypeRes.labelKey
                        col.options = dataTypeRes.options
                        col.format =  dataTypeRes.format
                        if(['rate','switch'].includes(component.type)){
                            col.setting = component
                        }
                        fields.push(col)
                    }
                })
            })
            return fields
        },

        handleSettingCondition(){
            if(this.config.moduleId){
                const module = this.modules.find(t=>t.f_ModuleId == this.config.moduleId)
                if(module.f_Target == 'custmerForm'){
                    this.formVisible = true
                }
                else{
                    this.$message({
                        type: 'warning',
                        message: '目前只支持自定义表单功能设置条件!'
                    })
                }
            }
            else{
                this.$message({
                    type: 'warning',
                    message: '请设置跳转功能!'
                })
            }
        },
        async handleSave(){
            if(this.$refs.form.validateForm()){
                this.config.conditionInfo = this.$refs.form.getForm()
                this.formVisible = false
            }
        },
        handleCloseForm(){
            this.$refs.form.resetForm()
        },
        handleOpenedForm(){
            this.$refs.form.setForm(this.config.moduleId,this.config.conditionInfo)
        },

        handleChangeSelect(event,item){
            //console.log(event,item,'event,item')
            item.dataType = event.dataType
            item.dataCode = event.code
            item.valueKey = event.valueKey
            item.labelKey = event.labelKey
            item.options = event.options
            item.format =  event.format
            item.setting = event.setting
        },

        // 表格
        // 获取组件数据类型
        getComponentDataType(compt){
            const res = {}
            if(['radio','checkbox','select','selectMultiple','treeselect','layerselect'].includes(compt.type)){
                switch(compt.dataType){
                    case '1':
                        res.dataType = 'mydata'
                        res.options = compt.options
                        break;
                    case '2':
                        res.dataType = 'dataItem'
                        res.code = compt.dataCode
                        break;
                    case '3':
                        res.dataType = 'dataSource'
                        res.code = compt.dataCode
                        res.valueKey = compt.dataValueKey
                        res.labelKey = compt.dataLabelKey 
                        break;   
                }
            }
            else if(['datetime','createtime','modifytime'].includes(compt.type)){
                res.dataType = 'datetime'
                res.format = compt.format || 'yyyy-MM-dd HH:mm:ss'
            }
            else if(['upload'].includes(compt.type)){
                res.dataType = 'file'
            }
            else if(['uploadimg'].includes(compt.type)){
                res.dataType = 'img'
            }
            else if(['companySelect','company'].includes(compt.type)){
                res.dataType = 'company'
            }
            else if(['departmentSelect','department'].includes(compt.type)){
                res.dataType = 'department'
            }
            else if(['userSelect','createuser','modifyuser'].includes(compt.type)){
                res.dataType = 'user'
            }
            else if(['areaselect'].includes(compt.type)){

                res.dataType = 'areas'
            }
            else {
                res.dataType = compt.type
            }
            return res
        }
    }
}
</script>

